import json
import re
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QMessageBox
from control.Databasemanage import DatabaseManager
from test_api import getdir
from threadmange.beganRJThread import WorkerThread
from view import select
import logging

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别
    filename="app.log",  # 日志文件名
    filemode="a",  # 追加模式
    format="%(asctime)s - %(levelname)s - %(message)s"  # 日志格式
)

db_manager = DatabaseManager()
db_manager.connect()
cursor = db_manager.connection.cursor()

class Select(select.Ui_Dialog, QDialog):
    def __init__(self, mainwindows):
        super(Select, self).__init__()
        self.mainwindows = mainwindows
        self.setupUi(self)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.pushButton.clicked.connect(self.close_button)  # 连接关闭窗口按钮

        logging.debug("Loading settings from file")
        self.settings_file = getdir() + 'api/ConfigJson.txt'
        try:
            with open(self.settings_file, 'r', encoding='utf-8') as file:
                settings = json.load(file)
            self.label_3.setText(settings["year"])
            self.label_5.setText(self.mainwindows.comboBox_2.currentText())
            self.label_7.setText(self.mainwindows.comboBox_3.currentText())
        except Exception as e:
            logging.error(f"Failed to load settings: {e}")
            QMessageBox.critical(self, "错误", "加载设置失败，请检查配置文件")

        self.pushButton_21.clicked.connect(self.begin_score)
        self.pushButton_22.clicked.connect(self.pause_score)
        self.pushButton_23.clicked.connect(self.stop_score)
        self.completed_tasks = []
        self.set_data()

    def set_data(self):
        logging.debug("Setting data")
        subject = self.mainwindows.comboBox_2.currentText()
        if subject == "请选择科目":
            logging.error("Subject not selected")
            QMessageBox.critical(self, "错误", "请先选择科目")
            return
        try:
            match = re.search(r'\(([^)]+)\)', subject)
            subject_code = match.group(1)
        except Exception as e:
            logging.error(f"Failed to extract subject code: {e}")
            QMessageBox.critical(self, "错误", "无法提取科目代码")
            return

        answer_qr_code = self.mainwindows.comboBox_3.currentText()
        if answer_qr_code == "选择阅卷答题":
            logging.error("Answer QR code not selected")
            QMessageBox.critical(self, "错误", "请选择小题")
            return

        try:
            question_type = answer_qr_code.split("、")[1]
            section_number = answer_qr_code.split("、")[0]
            if question_type == "单选题":
                question_type = "1"
            elif question_type == "多选题":
                question_type = "2"
            elif question_type == "判断题":
                question_type = "3"
        except Exception as e:
            logging.error(f"Failed to process answer QR code: {e}")
            QMessageBox.critical(self, "错误", "无法处理答题信息")
            return

        try:
            converted_section_number = self.convert_chinese_to_arabic(section_number)
            new_value = f"{question_type}{converted_section_number}"
        except Exception as e:
            logging.error(f"Failed to convert section number: {e}")
            QMessageBox.critical(self, "错误", "无法转换大题号")
            return

        query = "SELECT file_url_local, split_answer_status  FROM exam_scan_split WHERE subject_code = ? AND answer_qr_code = ?"
        try:
            cursor.execute(query, (subject_code, new_value))
            rows = cursor.fetchall()
            self.label_9.setText(str(len(rows)))
        except Exception as e:
            logging.error(f"Failed to execute query: {e}")
            QMessageBox.critical(self, "错误", "数据库查询失败")
            return

        logging.debug("Grouping tasks")
        self.group_0 = []
        self.group_1 = []
        self.group_2 = []
        for file_path, group_id in rows:
            if group_id == 0:
                self.group_0.append(file_path)
            elif group_id == 1:
                self.group_1.append(file_path)
            elif group_id == 2:
                self.group_2.append(file_path)

        self.total_task_number = str(len(rows))
        self.success_task_number = str(len(self.group_1))
        self.failed_task_number = str(len(self.group_2))
        self.incomplete_task_number = str(len(self.group_0))

        self.label_10.setText(f"共有任务{self.total_task_number}, 已成功{self.success_task_number}, 失败{self.failed_task_number}, 未完成{self.incomplete_task_number}")

        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(int(self.total_task_number))
        self.progressBar.setValue(int(self.total_task_number) - int(self.incomplete_task_number))

    def begin_score(self):
        logging.debug("Starting scoring")
        self.pushButton_21.setText("正在进行")
        try:
            logging.debug("Initializing worker thread")
            self.worker = WorkerThread(self.group_0, self.completed_tasks)
            logging.debug("Connecting signals to slots")
            self.worker.result_signal.connect(self.on_thread_finished)
            self.worker.error_signal.connect(self.Marking_error)
            self.worker.success_signal.connect(self.Mark_correctly)
            self.worker.stop_signal.connect(self.stop_worker)
            self.worker.finishedmessage.connect(self.finish)
            logging.debug("Starting worker thread")
            self.worker.start()
        except Exception as e:
            logging.error(f"Failed to start worker thread: {e}")
            QMessageBox.critical(self, "错误", "启动评分线程失败")

    def finish(self):
        logging.debug("Scoring finished")
        QMessageBox.information(self, "消息", "所有评分任务已完成")

    def stop_worker(self):
        logging.debug("Stopping worker")
        QMessageBox.information(self, "信息", "评分任务已停止")

    def on_thread_finished(self, result):
        logging.debug("Thread finished")
        if result:
            QMessageBox.information(self, '提示', '已阅完成')

    def pause_score(self):
        logging.debug("Pausing scoring")
        self.pushButton_21.setText("开始任务")
        print("暂停评分")

    def stop_score(self):
        logging.debug("Stopping scoring")
        self.pushButton_21.setText("开始任务")
        try:
            self.worker.stop()
        except Exception as e:
            logging.error(f"Failed to stop worker thread: {e}")
            QMessageBox.critical(self, "错误", "停止评分线程失败")

    def Marking_error(self, filepath):
        logging.error(f"Marking error: {filepath}")
        self.failed_task_number = str(int(self.failed_task_number) + 1)
        self.incomplete_task_number = str(int(self.incomplete_task_number) - 1)
        self.label_10.setText(f"共有任务{self.total_task_number}, 已成功{self.success_task_number}, 失败{self.failed_task_number}, 未完成{self.incomplete_task_number}")
        self.progressBar.setValue(int(self.total_task_number) - int(self.incomplete_task_number))
        self.textBrowser.append(str(f"识别{filepath}   失败"))

    def Mark_correctly(self, filepath):
        logging.debug(f"Marking correctly: {filepath}")
        self.success_task_number = str(int(self.success_task_number) + 1)
        self.incomplete_task_number = str(int(self.incomplete_task_number) - 1)
        self.label_10.setText(f"共有任务{self.total_task_number}, 已成功{self.success_task_number}, 失败{self.failed_task_number}, 未完成{self.incomplete_task_number}")
        self.progressBar.setValue(int(self.total_task_number) - int(self.incomplete_task_number))
        self.textBrowser.append(str(f"识别{filepath}   成功"))

    def convert_chinese_to_arabic(self, chinese_number):
        logging.debug(f"Converting {chinese_number} to arabic")
        chinese_to_arabic = {
            '一': '1', '二': '2', '三': '3', '四': '4',
            '五': '5', '六': '6', '七': '7', '八': '8',
            '九': '9', '十': '10'
        }
        return chinese_to_arabic.get(chinese_number, '0')

    def close_button(self):
        logging.debug("Closing window")
        self.close()